import 'dart:typed_data';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:get/get.dart';



class ImageView extends StatefulWidget {
  final String? imageUrl;
  final double? width;
  final double? height;
  final Color? backgroundColor;
  final BoxFit? fit;
  final Widget? placeholder;
  final double radius;
  final BorderRadius? borderRadius;
  final LoadStateChanged? loadStateHandler;
  final String? imageCacheName;
  final Color? color;
  final ExtendedImageMode mode;
  final DoubleTap? onDoubleTap;
  final InitGestureConfigHandler? initGestureConfigHandler;
  final int? cacheWidth;
  final int? cacheHeight;
  final int? maxBytes;
  final BoxBorder? border;
  final bool? enableSlideOutPage;
  final bool? openDefinePlaceholder;
  final bool clearMemoryCacheWhenDispose;
  final bool isNeedDecryption;
  final bool showFailReload;
  final AlignmentGeometry alignment;

  const ImageView({
    Key? key,
    this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.placeholder,
    this.radius = 0.0,
    this.borderRadius,
    this.backgroundColor,
    this.loadStateHandler,
    this.imageCacheName,
    this.mode = ExtendedImageMode.none,
    this.onDoubleTap,
    this.color,
    this.initGestureConfigHandler,
    this.cacheWidth,
    this.cacheHeight,
    this.maxBytes,
    this.border,
    this.openDefinePlaceholder = false,
    this.enableSlideOutPage,
    this.clearMemoryCacheWhenDispose = true,
    this.isNeedDecryption = true,
    this.showFailReload = false,
    this.alignment = Alignment.center,
  }) : super(key: key);

  @override
  State<ImageView> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView> {
  // late Future<Uint8List?> _future;

  @override
  void initState() {
    super.initState();
    // _future = getImageCache();
  }

  // Future<Uint8List?> getImageCache() async {
  //   // try {
  //   String imgUrl = (widget.imageUrl ?? "");
  //   if (imgUrl.contains("?")) {
  //     imgUrl = imgUrl.split("?").first;
  //   }
  //
  //   Uint8List? imageDecryption =
  //       await UtilsDecryption.cacheDownLoadAndDecrypt(imgUrl);
  //   if (imageDecryption != null) {
  //     return imageDecryption;
  //   } else {
  //     return Uint8List(0);
  //   }
  //
  //   // String cacheKey = keyToMd5(imgUrl);
  //   // final provider = ExtendedNetworkImageProvider(widget.imageUrl ?? '',
  //   //     cache: true, cacheKey: cacheKey);
  //   // // 加载图片并缓存
  //   //
  //   // Uint8List? datas = await provider.getNetworkImageData();
  //   //
  //   // clog('图片大小   ${(datas?.length ?? 0) / 1024}Kb');
  //   //
  //   // if (datas != null) {
  //   //   // 记录解密开始时间
  //   //   final startTime = DateTime.now();
  //   //   Uint8List? imageDecryption =
  //   //       UtilsDecryption.decryptAES128CBC(datas, widget.imageUrl ?? '');
  //   //   // 记录解密结束时间
  //   //   final endTime = DateTime.now();
  //   //   // 计算耗时
  //   //   final duration = endTime.difference(startTime);
  //   //   clog('解密耗时: ${duration.inMilliseconds}毫秒');
  //   //
  //   //   if (imageDecryption != null) {
  //   //     return imageDecryption;
  //   //   } else {
  //   //     return Future.error('加载错误');
  //   //   }
  //   // }
  //   // return Future.error('加载错误');
  //   // } catch (e) {
  //   //   return Future.error('加载错误');
  //   // }
  // }

  @override
  Widget build(BuildContext context) {
    final isNullOrBlank = GetUtils.isNullOrBlank(widget.imageUrl) ?? true;
    final isUrl = GetUtils.isURL(widget.imageUrl ?? '');

    if (isNullOrBlank || !isUrl) {
      return const SizedBox();
    }

    return buildImage();
  }

  Widget buildImage() {
    // return Container();
    double buildWidth = widget.width ?? widget.radius * 2;
    double buildHeight = widget.height ?? widget.radius * 2;
    String imgUrl = widget.imageUrl?.split("?").first ?? "";
    String cacheKey = keyToMd5(imgUrl);
    // ImageProvider
    return ExtendedImage.network(

      cacheKey: cacheKey,
      widget.imageUrl ?? '',
      width: (buildWidth > 0) ? buildWidth : null,
      height: (buildHeight > 0) ? buildHeight : null,
      fit: widget.fit ?? BoxFit.cover,
      alignment: widget.alignment,
      cache: true,
      color: widget.color,
      enableSlideOutPage: widget.enableSlideOutPage ?? false,
      shape: BoxShape.rectangle,
      borderRadius: (widget.radius > 0)
          ? BorderRadius.circular(widget.radius)
          : widget.borderRadius,
      imageCacheName: widget.imageCacheName,
      onDoubleTap: widget.onDoubleTap,
      mode: widget.mode,
      initGestureConfigHandler: widget.initGestureConfigHandler,
      loadStateChanged: (state) {
        if (widget.loadStateHandler != null) {
          return widget.loadStateHandler?.call(state);
        } else {
          if (state.extendedImageLoadState == LoadState.failed) {
            return _buildImageLoadFail(state);
          } else if (state.extendedImageLoadState == LoadState.loading) {
            return widget.placeholder ;
          }
          return null;
        }
      },
      cacheWidth: widget.cacheWidth,
      cacheHeight: widget.cacheHeight,
      maxBytes: widget.maxBytes,
      border: widget.border,
      clearMemoryCacheWhenDispose: widget.clearMemoryCacheWhenDispose,
    );
  }

  Widget _buildImageLoadFail(ExtendedImageState state) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        height: 1.sw,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  LocaleKeys.image_load_failed.tr,
                  style: TextStyle(
                    color: AppColor.hex('6F93BD'),
                    fontSize: 10.sp,
                  ),
                ),
                4.horizontalSpace,
                Icon(
                  Icons.refresh,
                  weight: 16.w,
                  color: AppColor.hex('6F93BD'),
                )
              ],
            ).marginOnly(top: 12.w)
          ],
        ),
      ),
      onTap: () {
        state.reLoadImage();
        // _future = getImageCache();
        // if (mounted) {
        //   setState(() {});
        // }
      },
    );
  }

}
